##################################################################
# File : /lua/ui/network/loginserver.lua
# Description : Dark Skies networking module
# Author : Neruz
##################################################################

local internalComm = import('/lua/ui/network/lobbycomm.lua')

local _Database = {Neruz = {password = tostring(string.hash("pass")), email = "neruz@index.hu"}} # temp database for tests

LoginServer = Class(internalComm.LobbyComm) {

	DataReceived = function(self, data)
		local _type = data._type
		local senderId = data.SenderID
		local senderName = data.SenderName
		
		if _type == "RequestLogin" then
			LOG('LoginServer Login', repr(data.login))
			local accountName = data.login.accountName
			local passwordHash = tostring(data.login.passwordHash)
			# TODO: check all the data in the database before returning the
			# (server uptime + password hash) hash
			local userExists = true
			# Temp usercheck
			if _Database[accountName]["password"] == passwordHash then 
				userExists = true
			end
			if userExists then
				local confirmationHash = string.hash(string.sub(tostring(GetSystemTimeSeconds()), 1, 4) .. passwordHash)
				self:SendData(senderId, {_type = "LoginValid", login = {confirmationHash = confirmationHash}})
			else
				self:SendData(senderId, {_type = "LoginInvalid", login = {reason = "Account or password is invalid"}})
			end
		elseif _type == "RegisterAccount" then
			LOG('LoginServer Register', repr(data.registration))
			local accountName = data.registration.accountName
			local passwordHash = tostring(data.registration.passwordHash)
			local email =  data.registration.email
			
	 		local accountNameValid = (accountName:len() != 0 and accountName:len() < 16 and accountName:isascii())
	 		local passwordValid = (passwordHash:len() != 0 and passwordHash:len() < 12 and passwordHash:isascii())
	 		local emailValid = (email:len() != 0 and email:isemail())
			
	 		if accountNameValid and passwordValid and emailValid then
	 			_Database[accountName] = {}
	 			_Database[accountName]["password"] = passwordHash
	 			_Database[accountName]["email"] = email
	 			self:SendData(senderId, {_type = "RegistrationValid", registration = {accountName = accountName}})
	 		else
	 			self:SendData(senderId, {_type = "RegistrationInvalid", registration = {reason = "Yea, sure."}})
	 		end
		end
	end,
}

function InitLoginServer(protocol, port)
    local comm = LoginServer(protocol, port, internalComm.maxConnections, "loginServer", nil, nil)
    return comm
end